import BaseVenueProcessor from './BaseVenueProcessor.js';
import { getJinManGuanHuangGuanVenueSettings } from '../request.js';

/**
 * 金满贯(皇冠假日)网球场地数据处理器
 */
export class JinManGuanHuangGuanProcessor extends BaseVenueProcessor {
  constructor() {
    super();
    this.venueName = '金满贯(皇冠假日)';
  }

  /**
   * 获取金满贯(皇冠假日)网球场地预约设置
   * @param {Object} params - 查询参数 { startDate, endDate }
   * @returns {Promise} 请求Promise
   */
  async getVenueSettings(params = {}) {
    // 设置默认参数
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    
    const defaultParams = {
      startDate: today,
      endDate: tomorrow
    };
    
    // 合并参数
    const requestData = { ...defaultParams, ...params };
    
    return await getJinManGuanHuangGuanVenueSettings(requestData);
  }

  /**
   * 验证数据是否有效
   * @param {Object} data - 原始场地数据
   * @returns {boolean} 数据是否有效
   */
  validateData(data) {
    return data && 
           data.data && 
           data.data.data && 
           data.data.data.courtList && 
           Array.isArray(data.data.data.courtList);
  }

  /**
   * 按场地名称分组
   * @param {Object} data - 原始场地数据
   * @returns {Map} 场地Map
   */
  groupVenues(data) {
    const venueMap = new Map();
    
    // 根据courtList数据创建场地分组
    data.data.data.courtList.forEach(court => {
      const venueName = court.subClassroomName || `${court.number}号场`;
      if (!venueMap.has(venueName)) {
        venueMap.set(venueName, {
          name: venueName,
          dataSource: this.venueName,
          timeSlots: [],
          courtId: court.number,
          maxPeople: 4, // 网球场默认4人
          pic: '', // 可以后续添加图片
          subClassroomNumber: court.number
        });
      }
    });
    
    return venueMap;
  }

  /**
   * 处理时间槽
   * @param {Map} venueMap - 场地Map
   * @param {Object} data - 原始场地数据
   */
  processTimeSlots(venueMap, data) {
    // 定义时间段，从7:00到22:00，每小时一个时间段
    const timeSlots = [];
    for (let hour = 7; hour <= 21; hour++) {
      const startTime = `${hour.toString().padStart(2, '0')}:00`;
      const endTime = `${(hour + 1).toString().padStart(2, '0')}:00`;
      timeSlots.push({
        time: `${startTime}-${endTime}`,
        startHour: hour,
        endHour: hour + 1
      });
    }

    // 遍历每个场地
    data.data.data.courtList.forEach(court => {
      const venueName = court.subClassroomName || `${court.number}号场`;
      const venue = venueMap.get(venueName);
      
      if (venue && court.list && Array.isArray(court.list)) {
        // 为每个时间段添加时间槽信息
        timeSlots.forEach((timeSlot, index) => {
          if (index < court.list.length) {
            const courtData = court.list[index];
            
            // status为0表示可预订，其他状态表示不可预订
            const isAvailable = courtData.status === 0;
            
            // 价格转换：1000表示100元
            const price = courtData.price ? Math.round(courtData.price / 100) : 0;
            
            venue.timeSlots.push({
              time: timeSlot.time,
              price: price,
              available: isAvailable,
              status: courtData.status,
              id: courtData.id,
              originalPrice: courtData.price
            });
          }
        });
      }
    });
  }

  /**
   * 转换为场地列表格式
   * @param {Map} venueMap - 场地Map
   * @returns {Array} 场地列表
   */
  convertToVenueList(venueMap) {
    const venueList = [];
    
    venueMap.forEach((venue) => {
      venueList.push({
        name: venue.name,
        dataSource: venue.dataSource,
        timeSlots: venue.timeSlots,
        courtId: venue.courtId,
        maxPeople: venue.maxPeople,
        pic: venue.pic,
        subClassroomNumber: venue.subClassroomNumber
      });
    });
    
    return venueList;
  }

  /**
   * 处理场地数据
   * @param {Object} data - 原始场地数据
   * @param {string} selectedDate - 选择的日期
   * @returns {Array} 处理后的场地列表
   */
  process(data, selectedDate) {
    if (!this.validateData(data)) {
      console.warn('金满贯(皇冠假日)数据验证失败:', data);
      return [];
    }

    const venueMap = this.groupVenues(data);
    this.processTimeSlots(venueMap, data);
    return this.convertToVenueList(venueMap);
  }
}

export default JinManGuanHuangGuanProcessor;